<!--  -->
<template>
  <div class="">
    <a-card>
      <div class="search-form-wrapper" ref="search">
        <a-form layout="inline">
          <a-row :gutter="48">
            <a-col :md="6" :sm="24">
              <a-form-item>
                <a-input
                  v-model="queryParam.name"
                  allow-clear
                  placeholder="指标名称"
                >
                </a-input>
              </a-form-item>
            </a-col>

            <a-col :md="6" :sm="24">
              <span class="table-page-search-submitButtons">
                <a-button type="primary" @click="loadData">查询</a-button>
                <a-button
                  style="margin-left: 8px"
                  @click="() => (queryParam = {})"
                >重置</a-button
                >
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
      <a-button
        type="primary"
        @click="addTarget"
        size="small"
        style="margin-bottom: 20px"
        v-if="userInfo.orgLayer == 1"
      >
        添加指标
      </a-button>
      <div class="target-list">
        <div
          class="target-item"
          v-for="(item, index) in targetList"
          :key="index"
        >
          <div class="target-item-title">
            <p class="text">{{ item.name }}</p>
            <a-switch
              checked-children="有效"
              un-checked-children="无效"
              v-model="item.statusValue"
              @change="statusChange(item)"
            ></a-switch>
          </div>
          <p class="target-item-desc">描述：{{ item.remark }}</p>
          <p class="target-item-temp">
            营销录入时间：每月{{ item.inputTimeStart }}日~{{
              item.inputTimeEnd
            }}日
          </p>
          <p class="target-item-temp">
            分行经办人：{{ item.handleUserName }}（{{ item.handleUserId }}）
          </p>
          <p class="target-item-temp">
            分行审核人：{{ item.auditUserName }}（{{ item.auditUserId }}）
          </p>
          <div class="target-item-act">
            <a-button
              type="primary"
              size="small"
              @click="netSet(item)"
              v-if="userInfo.orgLayer == 3 || userInfo.orgLayer == 2"
            >网点人员设置</a-button
            >
            <a-button
              size="small"
              type="primary"
              @click="subShow(item)"
              v-if="userInfo.orgLayer == 2"
            >支行人员设置</a-button
            >
            <a-button
              size="small"
              type="primary"
              @click="profitShow(item)"
              v-if="userInfo.orgLayer == 2"
            >设置默认比例</a-button
            >
            <a-button
              size="small"
              type="primary"
              @click="editTarget(item.id)"
              v-if="userInfo.orgLayer == 1"
            >
              编辑
            </a-button>
          </div>
        </div>
      </div>
    </a-card>
    <!-- 新增和编辑 -->
    <a-drawer
      :width="900"
      placement="right"
      :visible="visible"
      :after-visible-change="afterVisibleChange"
      @close="onClose"
      title="指标设置"
    >
      <a-form-model
        :model="addForm"
        ref="addForm"
        :rules="rules"
        :label-col="labelCol"
        :wrapper-col="wrapperCol"
      >
        <a-form-model-item label="指标名称：" prop="name">
          <a-input
            v-model="addForm.name"
            placeholder="请输入"
            allow-clear
          ></a-input>
        </a-form-model-item>
        <a-form-model-item label="指标ID：" prop="code">
          <a-input
            v-model="addForm.code"
            placeholder="请输入"
            allow-clear
          ></a-input>
        </a-form-model-item>
        <a-form-model-item label="指标描述：">
          <a-textarea
            :maxLength="100"
            v-model="addForm.remark"
            placeholder="请输入"
            allow-clear
          ></a-textarea>
        </a-form-model-item>
        <a-form-model-item label="营销数据录入时间：" prop="inputTimeStart">
          <div class="input-time">
            <span class="label">每月</span>
            <a-input
              v-model="addForm.inputTimeStart"
              placeholder="开始时间"
              allow-clear
            ></a-input>
            <span class="label">日～</span>
            <a-input
              v-model="addForm.inputTimeEnd"
              placeholder="结束时间"
              allow-clear
            ></a-input>
            <span class="label">日</span>
          </div>
        </a-form-model-item>
        <a-form-model-item label="营销数据认领时间：" prop="claimTimeEnd">
          <div class="input-time">
            <span class="label2">每月</span>
            <a-input v-model="addForm.claimTimeEnd" allow-clear></a-input>
            <span class="label2">日前</span>
          </div>
        </a-form-model-item>
        <a-form-model-item label="分行经办人：" prop="handleUserId">
          <a-select
            show-search
            class="select"
            v-model="addForm.handleUserId"
            placeholder="请选择"
            :filter-option="filterOption"
            allow-clear
          >
            <a-select-option
              :value="item.id"
              v-for="(item, index) in memberList"
              :key="index"
            >
              {{ item.name }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="分行审核人：" prop="auditUserId">
          <a-select
            show-search
            class="select"
            v-model="addForm.auditUserId"
            placeholder="请选择"
            :filter-option="filterOption"
            allow-clear
          >
            <a-select-option
              :value="item.id"
              v-for="(item, index) in memberList"
              :key="index"
            >
              {{ item.name }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="协作部门标识：" prop="identifiesTypes">
          <a-select
            mode="multiple"
            placeholder="请选择"
            v-model="addForm.identifiesTypes"
            @change="handleChange"
          >
            <a-select-option v-for="i in identifiesTypeList" :key="i.dictValue">
              {{ i.dictLabel }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="存量单位计价比例：" prop="stockUnitValRatio">
          <a-input
            v-model="addForm.stockUnitValRatio"
            placeholder="请输入"
            allow-clear
          ></a-input>
        </a-form-model-item>
        <a-form-model-item label="新增单位计价比例：" prop="newUnitValRatio">
          <a-input
            v-model="addForm.newUnitValRatio"
            placeholder="请输入"
            allow-clear
          ></a-input>
        </a-form-model-item>
        <a-form-model-item :wrapper-col="{ span: 13, offset: 3 }">
          <a-button type="primary" @click="addSubmit">保存</a-button>
          <a-button @click="onClose">取消</a-button>
        </a-form-model-item>
      </a-form-model>
    </a-drawer>
    <!-- 网点人员设置 -->
    <a-drawer
      :width="900"
      placement="right"
      :visible="netVisible"
      :after-visible-change="afterVisibleChange"
      @close="onClose"
      title="网点人员设置"
    >
      <div class="net-table">
        <div class="net-table-header">
          <div class="net-table-header-item">网点</div>
          <div
            class="net-table-header-item"
            v-for="(item, index) in netList"
            :key="index"
          >
            {{ item.identifiesTypeDesc }}经办人
          </div>
        </div>
        <div class="net-table-content">
          <div
            class="net-table-content-item"
            v-for="(item, index) in netData"
            :key="index"
          >
            <div class="name">{{ item.orgName }}</div>
            <div
              class="value"
              v-for="(temp, tempIndex) in netList"
              :key="tempIndex"
            >
              <a-select
                show-search
                class="select"
                v-model="item[temp.identifiesType]"
                placeholder="请输入员工姓名或者统一认证号"
                @search="fetchUser2"
                @focus="fetchUser2(null, item.orgCode, 'net')"
                @blur="clearOrgId"
                :filter-option="false"
                allow-clear
                style="width: 100%"
              >
                <a-select-option
                  :value="i.id"
                  v-for="(i, iIndex) in memberList2"
                  :key="iIndex"
                >
                  {{ i.name }}
                </a-select-option>
              </a-select>
              <!-- <a-input
                v-model="item[temp.identifiesType]"
                placeholder="请输入员工姓名或者统一认证号"
              ></a-input> -->
            </div>
          </div>
        </div>
        <div class="net-act">
          <a-button type="primary" @click="netSubmit">保存</a-button>
          <a-button @click="onClose">取消</a-button>
        </div>
      </div>
    </a-drawer>
    <!-- 支行人员设置 -->
    <a-drawer
      :width="900"
      placement="right"
      :visible="subVisible"
      :after-visible-change="afterVisibleChange"
      @close="onClose"
      :title="'支行人员设置' + '（' + subBankName + '）'"
    >
      <a-form-model
        :model="subForm"
        ref="subForm"
        :rules="subRules"
        :label-col="labelCol"
        :wrapper-col="wrapperCol"
      >
        <a-form-model-item label="经办人：" prop="handleUserId">
          <a-select
            show-search
            class="select"
            v-model="subForm.handleUserId"
            placeholder="请选择"
            @search="fetchUser"
            @focus="fetchUser"
            :filter-option="false"
            allow-clear
          >
            <a-select-option
              :value="item.id"
              v-for="(item, index) in memberList2"
              :key="index"
            >
              {{ item.name }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="审核人：" prop="auditUserId">
          <a-select
            show-search
            class="select"
            v-model="subForm.auditUserId"
            :filter-option="false"
            @search="fetchUser"
            @focus="fetchUser"
            placeholder="请选择"
            allow-clear
          >
            <a-select-option
              :value="item.id"
              v-for="(item, index) in memberList2"
              :key="index"
            >
              {{ item.name }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item :wrapper-col="{ span: 13, offset: 3 }">
          <a-button type="primary" @click="subSubmit">保存</a-button>
          <a-button @click="onClose">取消</a-button>
        </a-form-model-item>
      </a-form-model>
    </a-drawer>
    <!-- 默认分润比例设置 -->
    <a-drawer
      :width="900"
      placement="right"
      :visible="profitVisible"
      :after-visible-change="afterVisibleChange"
      @close="onClose"
      :title="'默认分润比例设置' + '（' + subBankName + '）'"
    >
      <a-form-model
        :model="profitForm"
        ref="profitForm"
        :rules="profitRules"
        :label-col="labelCol"
        :wrapper-col="wrapperCol"
      >
        <a-form-model-item
          v-for="(item, index) in profitList"
          :key="index"
          :label="item.identifiesTypeDesc + '现分润比例：'"
          :prop="item.identifiesType"
        >
          <a-input
            v-model="profitForm[item.identifiesType]"
            placeholder="请输入"
            allow-clear
          ></a-input>
        </a-form-model-item>
        <a-form-model-item :wrapper-col="{ span: 13, offset: 3 }">
          <a-button type="primary" @click="profitSubmit">保存</a-button>
          <a-button @click="onClose">取消</a-button>
        </a-form-model-item>
      </a-form-model>
    </a-drawer>
  </div>
</template>

<script>
import {
  getTargetList,
  // getDictData,
  getUserMemberList,
  addTarget,
  getTargetInfo,
  getNetworkHandle,
  getHandleAuditor,
  setHandleAuditor,
  getProfit,
  setProfit,
  getIdentifiesTypes,
  setNetUser
} from '@/api/system'
import { mapGetters } from 'vuex'
export default {
  data () {
    return {
      visible: false,
      pagination: {
        current: 1,
        'show-size-changer': true,
        total: 0
      },
      tableLoading: false,
      advanced: false,
      queryParam: {},
      tabbarHeight: 420,
      queryParamKey: 'spu_name',
      addForm: {},
      netForm: {},
      labelCol: { span: 5 },
      wrapperCol: { span: 13 },
      rules: {
        name: [{ required: true, message: '请输入指标名称' }],
        code: [{ required: true, message: '请输入指标ID' }],
        inputTimeStart: [{ required: true, message: '请输入营销数据录入时间' }],
        claimTimeEnd: [{ required: true, message: '请输入营销数据认领时间' }],
        handleUserId: [{ required: true, message: '请选择分行经办人' }],
        auditUserId: [{ required: true, message: '请选择分行审核人' }],
        identifiesTypes: [{ required: true, message: '请选择协作部门标识' }],
        stockUnitValRatio: [
          { required: true, message: '请输入存量单位计价比例' }
        ],
        newUnitValRatio: [{ required: true, message: '请输入新增单位计价比例' }]
      },
      subRules: {
        handleUserId: [{ required: true, message: '请选择经办人' }],
        auditUserId: [{ required: true, message: '请选择审核人' }]
      },
      profitRules: {
        handleUserId: [{ required: true, message: '请输入网点现分润比例' }]
        // handleUserId: [{ required: true, message: '请输入网点现分润比例' }],
        // handleUserId: [{ required: true, message: '请输入网点现分润比例' }],
        // handleUserId: [{ required: true, message: '请输入网点现分润比例' }],
      },
      netVisible: false,
      targetList: [],
      identifiesTypeList: [],
      memberList: [],
      subVisible: false,
      subForm: {},
      subBankName: '',
      memberList2: [],
      profitForm: {},
      profitVisible: false,
      profitList: [],
      profitData: {},
      netList: [],
      netData: [],
      netOrgId: ''
    }
  },
  computed: {
    hasSelected () {
      return this.selectedRowKeys.length > 0
    },
    tableHeight () {
      return document.body.clientHeight - 220
    },
    ...mapGetters(['userInfo'])
  },
  components: {},
  activated () {
    this.loadData()
    // this.fechDictData()
    this.getMemberList()
    this.getMemberList2()
    console.log(this.userInfo)
  },
  methods: {
    afterVisibleChange (val) {
      console.log('visible', val)
    },
    showDrawer () {
      this.visible = true
    },
    onClose () {
      this.visible = false
      this.netVisible = false
      this.subVisible = false
      this.profitVisible = false
    },
    loadData () {
      this.tableLoading = true

      getTargetList({ ...this.queryParam })
        .then((res) => {
          this.tableLoading = false
          console.log(res)
          res.rows.forEach((item) => {
            item.statusValue = item.status == 1
          })
          this.targetList = res.rows
          this.pagination.total = res.total
        })
        .catch(() => {})
    },
    handle (v) {
      console.log('daozhegel')

      if (v && v.current) {
        if (this.queryParam.page_size == v.pageSize) {
          this.pagination.current = v.current
          this.queryParam.page_no = v.current
        } else {
          this.queryParam.page_size = v.pageSize
          this.queryParam.page_no = 1
          this.pagination.current = 1
        }
      } else {
        this.queryParam.page_no = 1
        this.pagination.current = 1
      }

      this.loadData()
    },
    toggleAdvanced () {
      this.advanced = !this.advanced
    },
    addTarget () {
      this.showDrawer()
    },
    editTarget (id) {
      console.log(id)
      this.getTargetInfo(id)
      this.showDrawer()
    },
    // fechDictData () {
    //   getDictData('identifiesType').then((res) => {
    //     this.identifiesTypeList = res.data
    //   })
    // },
    handleChange (info) {},
    filterOption (input, option) {
      return (
        option.componentOptions.children[0].text
          .toLowerCase()
          .indexOf(input.toLowerCase()) >= 0
      )
    },
    filterOption2 (input, option) {
      console.log(input, option)
      return (
        option.componentOptions.children[0].text
          .toLowerCase()
          .indexOf(input.toLowerCase()) >= 0
      )
    },
    getMemberList () {
      getUserMemberList().then((res) => {
        console.log(res)
        this.memberList = res.data
      })
    },
    getMemberList2 (name) {
      this.memberList2 = []
      const data = {
        name: name || ''
      }
      // console.log(this.netOrgId)
      // if (this.netOrgId) {
      //   data.orgId = this.netOrgId
      // }

      getUserMemberList(data).then((res) => {
        this.memberList2 = res.data
      })
    },
    getMemberList3 (name) {
      this.memberList2 = []
      const data = {
        name: name || ''
      }
      console.log(this.netOrgId)
      if (this.netOrgId) {
        data.orgCode = this.netOrgId
      }

      getUserMemberList(data).then((res) => {
        this.memberList2 = res.data
      })
    },
    addSubmit () {
      console.log(this.addForm)
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          addTarget(this.addForm).then((res) => {
            console.log(res)
            this.$notification['success']({
              message: '提示',
              description: `${this.addForm.id ? '编辑' : '新增'}成功`
            })
            this.onClose()
            this.loadData()
          })
        }
      })
    },
    getTargetInfo (id) {
      getTargetInfo(id).then((res) => {
        this.addForm = res.data
      })
    },
    statusChange (info) {
      console.log(info)
      info.status = info.status == '0' ? '1' : '0'
      addTarget(info).then((res) => {
        console.log(res)
        this.$notification['success']({
          message: '提示',
          description: '编辑状态成功'
        })
        this.loadData()
      })
    },
    netSet (info) {
      console.log(info)
      this.netVisible = true
      this.getNetworkHandle(info)
    },
    getNetworkHandle (info) {
      getNetworkHandle({
        indexCode: info.code
      }).then((res) => {
        console.log(res)
        res.data.forEach((item) => {
          item.users.forEach((temp) => {
            item[temp.identifiesType] = temp.handleUserId
          })
        })
        this.netData = res.data
      })

      getIdentifiesTypes({
        indexCode: info.code
      }).then((res) => {
        console.log(res)
        this.netList = res.data
      })
    },
    getHandleAuditor (info) {
      getHandleAuditor({
        indexCode: info.code
      }).then((res) => {
        console.log(res)
        this.subForm = res.data
        this.subBankName = res.data ? res.data.orgName : ''
        this.subForm.indexCode = info.code
      })
    },
    fetchUser (input, id, type) {
      this.getMemberList2(input)
    },
    fetchUser2 (input, id, type) {
      console.log(input, id)
      if (!input && id && type == 'net') {
        this.netOrgId = id
      }
      this.getMemberList3(input)
    },
    clearOrgId () {
      // this.netOrgId = null
    },
    subShow (info) {
      this.subVisible = true
      this.subForm.indexCode = info.code
      this.getHandleAuditor(info)
    },
    subSubmit () {
      console.log(this.subForm)
      this.$refs.subForm.validate((valid) => {
        if (valid) {
          setHandleAuditor(this.subForm).then((res) => {
            console.log(res)
            this.$notification['success']({
              message: '提示',
              description: `${this.subForm.id ? '编辑' : '新增'}支行人员成功`
            })
            this.onClose()
            this.loadData()
          })
        }
      })
    },
    profitShow (info) {
      this.getProfit(info)
      this.profitVisible = true
    },
    getProfit (info) {
      getProfit({
        indexCode: info.code
      }).then((res) => {
        console.log(res)
        this.subBankName = res.data.orgName
        this.profitList = res.data.indexConfigBranchProfits
        const profitRules = {}
        const profitForm = {}
        res.data.indexConfigBranchProfits.forEach((item) => {
          profitRules[item.identifiesType] = [
            {
              required: true,
              message: '请输入' + item.identifiesTypeDesc + '现分润比例'
            }
          ]
          profitForm[item.identifiesType] = item.ratio
        })
        this.profitRules = profitRules
        this.profitForm = profitForm
        this.profitData = res.data
      })
    },
    profitSubmit () {
      this.$refs.profitForm.validate((valid) => {
        if (valid) {
          this.profitList.forEach((item) => {
            item.ratio = this.profitForm[item.identifiesType]
          })
          this.profitData.indexConfigBranchProfits = this.profitList
          setProfit(this.profitData).then((res) => {
            console.log(res)
            this.$notification['success']({
              message: '提示',
              description: '编辑分润比例成功'
            })
            this.onClose()
            this.loadData()
          })
        }
      })
    },
    netSubmit () {
      console.log(this.netData)
      console.log(this.netList)
      this.netData.forEach((item) => {
        const users = []
        this.netList.forEach((temp) => {
          users.push({
            handleUserId: item[temp.identifiesType],
            identifiesType: temp.identifiesType,
            identifiesTypeDesc: temp.identifiesTypeDesc
          })
        })
        item.users = users
      })
      setNetUser({ indexConfigNetworkOrgs: this.netData }).then((res) => {
        console.log(res)
        this.$notification['success']({
          message: '提示',
          description: '网点人员编辑成功'
        })
        this.onClose()
        this.loadData()
      })
    }
  }
}
</script>

<style lang="less" scoped>
.empty {
  width: calc(100% + 50px);
  margin-left: -25px;
  height: 12px;
  background: #f7f8fa;
}
.search-box {
  width: 100%;
  overflow-x: auto;
  overflow-y: hidden;
  min-height: 47px;
  margin-bottom: 19px;
  .type-list {
    display: flex;
    align-items: center;
    flex-wrap: nowrap;
    .type-item {
      height: 45px;
      line-height: 45px;
      border-bottom: 2px solid #fff;
      padding: 0 20px;
      font-size: 14px;
      cursor: pointer;
    }
    .type-item.active {
      border-bottom: 2px solid #4393F2;
      font-size: 16px;
      font-weight: 500;
      color: #4393F2;
    }
  }
}
.search-form-wrapper {
  background: #f3f4f7;
  padding: 10px 20px 0;
  margin-bottom: 20px;
  padding-bottom: 20px;
  /deep/ .ant-col {
    height: 45px;
  }
  /deep/ .ant-form-item {
    margin: 12px 0;
  }
  /deep/ .ant-btn {
    width: 68px;
    height: 32px;
    margin-top: 12px;
  }
}
.target-list {
  display: flex;
  flex-wrap: wrap;
  .target-item {
    width: calc(33.33% - 14px);
    // height: 250px;
    border: 1px solid #ccc;
    margin-bottom: 20px;
    padding: 8px;
    border-radius: 4px;
    p {
      margin: 0;
    }
    &-title {
      display: flex;
      justify-content: space-between;
      align-items: center;
      .text {
        font-size: 18px;
        font-weight: 600;
      }
      margin-bottom: 10px;
    }
    &-temp {
      height: 30px;
      line-height: 30px;
      width: 100%;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
    &-act {
      margin-top: 10px;
      .ant-btn {
        margin-bottom: 10px;
        margin-right: 10px;
        background: #fff;
        border: 1px solid #4393F2;
        color: #4393F2;
      }
    }
  }
  .target-item:nth-child(3n + 2) {
    margin: 0px 21px 20px 21px;
  }
}
.input-time {
  display: flex;
  align-items: center;
  .label {
    display: inline-block;
    width: 100px;
    text-align: center;
  }
  .label2 {
    display: inline-block;
    width: 50px;
    text-align: center;
  }
}
.net-table {
  .net-table-header {
    display: flex;
    &-item {
      flex: 1;
      text-align: center;
    }
  }
  .net-table-content {
    &-item {
      display: flex;
      width: 100%;
      align-items: center;
      justify-content: center;
      margin-top: 10px;
      .name {
        flex: 1;
        text-align: center;
      }
      .value {
        flex: 1;
        padding: 0 5px;
      }
    }
  }
}
.net-act {
  margin: 20px;
  .ant-btn {
    margin: 0 10px;
  }
}
</style>
